package com.zzyl.common.ai;

import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baidubce.qianfan.Qianfan;
import com.baidubce.qianfan.core.auth.Auth;
import com.baidubce.qianfan.model.chat.ChatResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class AIModelInvoker {

    @Autowired
    private Task task;

    public String qianfanInvoker(String prompt) {
        System.out.println(prompt);

        Map messageMap = Map.of("role","user","content",prompt);

        List messages = List.of(messageMap);

        Map bodyMap = new HashMap();
        bodyMap.put("model",task.getQianfanModel());
        bodyMap.put("max_output_tokens",task.getMaxOutputTokens());
        bodyMap.put("messages",messages);

        String body = HttpUtil.createRequest(Method.POST, task.getQianfanEndpoint())
                // 设置头
                .header("Authorization",task.getAuthorization())
                // 设置body参数
                .body(JSONUtil.toJsonStr(bodyMap))
                .execute().body();
        System.out.println(body);
        JSONObject jsonObject = JSONUtil.parseObj(body);
        String content = jsonObject.getByPath("choices[0].message.content", String.class);
        content = content.replace("```json", "");
        content = content.replace("```", "");

        return content;
    }

}